#-*-coding:utf-8 -*-
'''
Created on 2013-6-28

@author: Administrator
'''

import os

class Node(object):
    
    def __init__(self, sender):
        self.sender = sender
        self.count = 0
        self.children = {}
        self.orders = []
    
    def increment(self):
        self.count += 1
        
    def getChild(self, s):
        node = None
        if self.children.has_key(s):
            node = self.children[s]
        else:
            node = Node(s)
            self.children[s] = node
            
        node.increment()
        return node
    def __str__(self):
        return '{sender:%s, count: %d, children:%s}' % (self.sender, self.count, str(map(str, self.children.values()) ))
    
    def getCount(node):
        return node.count
    getCount = staticmethod(getCount)
        

class Tree(object):
    
    def __init__(self):
        self.tree = {}
    
    def addSender(self, sender):
        if sender.startswith('+86'):
            sender = sender[3:]
        
        if len(sender) <= 9:
            
            self.__getNode(sender)
        else:
            fs = sender[0:9]
            node = self.__getNode(fs)
            l = 11
            if len(sender) > 11:
                l = 11
            ss = sender[9:l]
            for s in ss:
                sNode = self.__getChildNode(node, s)
                node = sNode
            if len(sender) > 11:
                self.__getChildNode(node, sender[l:])
                
    def __getChildNode(self, parent, s):
        node = parent.getChild(s)
        return node
    
    def __getNode(self, sender):
        node = None
        if self.tree.has_key(sender):
            node = self.tree[sender]
        else:
            node = Node(sender)
            self.tree[sender] = node
        node.increment()
        return node
    
    def sorted(self):
        return sorted(self.tree.values(), key=Node.getCount)

def main():
    smsFile = open(r'E:/sms20130626.txt', 'r')
    result = open(r'E:/sms20130626_result.txt', 'w')
    tree = Tree()
    for sender in smsFile:
        tree.addSender(sender.strip('\r').strip('\n'))
    
    nodes = tree.sorted()
    result.write('{')
    result.writelines([str(node) for node in nodes])
    print len(nodes)
    result.write('}')
        
    result.flush()
    result.close()
    smsFile.close()
if __name__ == '__main__':
    print 'starting...'
    main()
        